import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Goods } from "../../entities/goods.entity";
import { TypeOrmCrudService } from '@nestjsx/crud-typeorm';

@Injectable()
export class GoodsService extends TypeOrmCrudService<Goods>{
  constructor(
    @InjectRepository(Goods)
    private goodsRepository: Repository<Goods>
  ){
    super(goodsRepository);
  }

  async getList(category_id: number, sort:any = {sort_order: "DESC"}, page: number = 1, limit: number = 10){
    let goods = await this.goodsRepository.find({
      where: {
        category_id: category_id
      },
      order:sort,
      skip: (page -1)*limit,
      take: limit,
    });
    let total:number = await this.goodsRepository.count({
      where: {
        category_id: category_id
      }
    });
    return  {
      goods: goods,
      page: page++,
      limit:limit,
      total:Math.ceil(total/limit)
    };
  }

  async getNewList(page: number = 1, limit: number = 10){
    let goods = await this.goodsRepository.find({
      where: {
        is_on_sale: 1,
        is_new: 1
      },
      order:{
        sort_order: "DESC"
      },
      skip: (page -1)*limit,
      take: limit,
    });
    let total:number = await this.goodsRepository.count({
      where: {
        is_on_sale: 1,
        is_new: 1
      }
    });
    return  {
      goods: goods,
      page: page++,
      limit:limit,
      total:Math.ceil(total/limit)
    };
  }

  async getHotList(page: number = 1, limit: number = 10){
    let goods = await this.goodsRepository.find({
      where: {
        is_on_sale: 1,
        is_hot: 1
      },
      order:{
        sort_order: "DESC"
      },
      skip: (page -1)*limit,
      take: limit,
    });
    let total:number = await this.goodsRepository.count({
      where: {
        is_on_sale: 1,
        is_hot: 1
      }
    });
    return  {
      goods: goods,
      page: page++,
      limit:limit,
      total:Math.ceil(total/limit)
    };
  }

}
